import { ref, reactive } from 'vue';
import type { Ref } from 'vue';
import { useWorkflowStore } from '@/stores/workflow';

/**
 * 画布平移和缩放功能组合式函数
 * @param svgContainer SVG容器元素引用
 */
export const useCanvasPanning = (svgContainer: Ref<SVGSVGElement | null>) => {
  const workflowStore = useWorkflowStore();
  
  // 状态管理
  const isPanning = ref(false);  // 是否正在平移
  const startPan = reactive({ x: 0, y: 0 });  // 平移起始位置
  const currentPan = reactive({ x: 0, y: 0 }); // 当前平移位置
  const scale = ref(1);  // 当前缩放比例
  
  // 缩放范围限制
  const minScale = 0.1;  // 最小缩放比例
  const maxScale = 2;    // 最大缩放比例

  // 添加框选状态管理
  const isSelecting = ref(false);
  const selectionStart = reactive({ x: 0, y: 0 });
  const selectionEnd = reactive({ x: 0, y: 0 });
  
  let longPressTimer: string | number | NodeJS.Timeout | null | undefined;

  
  // 添加选择框元素
  const createSelectionRect = () => {
    const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
    rect.setAttribute('class', 'selection-rect');
    rect.setAttribute('fill', 'rgba(64, 158, 255, 0.1)');
    rect.setAttribute('stroke', '#409EFF');
    rect.setAttribute('stroke-width', '1');
    return rect;
  };

  let selectionRect: SVGRectElement | null = null;

  // 添加一个坐标转换的工具方法
  const convertToSVGCoordinates = (clientX: number, clientY: number) => {
    if (!svgContainer.value) return { x: 0, y: 0 };
    const rect = svgContainer.value.getBoundingClientRect();
    return {
      x: (clientX - rect.left - currentPan.x) / scale.value,
      y: (clientY - rect.top - currentPan.y) / scale.value
    };
  };

  /**
   * 处理鼠标滚轮缩放
   * @param e 滚轮事件对象
   */
  const handleWheel = (e: WheelEvent) => {
    if (!svgContainer.value) return;
    e.preventDefault();
    
    // 获取鼠标相对于 SVG 的位置
    const rect = svgContainer.value.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    // 计算鼠标相对于当前平移后的位置
    const x = (mouseX - currentPan.x) / scale.value;
    const y = (mouseY - currentPan.y) / scale.value;

    // 计算新的缩放值
    const delta = e.deltaY > 0 ? 0.9 : 1.1;  // 缩放步长
    const newScale = Math.max(minScale, Math.min(maxScale, scale.value * delta));
    
    // 更新平移值以保持鼠标位置不变
    currentPan.x = mouseX - x * newScale;
    currentPan.y = mouseY - y * newScale;
    
    // 更新缩放值
    scale.value = newScale;

    updateTransform();
    
    // 缩放时触发视图更新
    workflowStore.incrementVersion();
  };

  /**
   * 处理画布鼠标按下事件
   * @param e 鼠标事件对象
   */
  const handleCanvasMouseDown = (e: MouseEvent) => {
	  

	//框选操作  
	if(e.button === 0){
		document.addEventListener('mousemove', handleSelectedCanvasMouseMove);
		document.addEventListener('mouseup', handleSelectedCanvasMouseUp);
		workflowStore.hideNodeMenu();
		workflowStore.hideNodePortMenu();
	}  
	else if(e.button === 2){
		startPan.x = e.clientX - currentPan.x;
		startPan.y = e.clientY - currentPan.y;
		longPressTimer = setTimeout(() => {
			isPanning.value = true;
			workflowStore.hideNodeMenu();
		}, 500); // 0.5秒
		document.addEventListener('mousemove', handleCanvasMouseMove);
		document.addEventListener('mouseup', handleCanvasMouseUp);
	}
  };

  /**
   * 处理画布鼠标移动事件
   * @param e 鼠标事件对象
   */
  const handleCanvasMouseMove = (e: MouseEvent) => {
	  if(longPressTimer!=null){
		  isPanning.value = true;
		  clearTimeout(longPressTimer); // 清除长按定时器
		  longPressTimer=null;
		  workflowStore.hideNodeMenu();
	  }
    if (!isPanning.value || !svgContainer.value) return;
    
    // 更新平移位置
    currentPan.x = e.clientX - startPan.x;
    currentPan.y = e.clientY - startPan.y;
    
    updateTransform();
  };
  
  /**
   * 处理画布鼠标松开事件
   * @param e 鼠标事件对象
   */
  const handleCanvasMouseUp = (e: MouseEvent) => {
	if(longPressTimer!=null){
		  clearTimeout(longPressTimer); // 清除定时器
		  longPressTimer=null;
	}
	
    if (e.button === 2 || e.type === 'mouseleave') {
		e.preventDefault();
	   if(isPanning.value==false){
		  workflowStore.showNodeMenu(e);
	   }	
      isPanning.value = false;
      document.removeEventListener('mousemove', handleCanvasMouseMove);
      document.removeEventListener('mouseup', handleCanvasMouseUp);
    }
  };
  
  /**
   * 更新SVG变换
   * 包括平移和缩放的应用，以及网格背景的更新
   */
  const updateTransform = () => {
    if (!svgContainer.value) return;

    // 更新内容容器的变换
    const contentGroup = svgContainer.value.querySelector('.content-group');
    if (contentGroup) {
      // 应用平移变换
      contentGroup.setAttribute('transform', 
        `translate(${currentPan.x},${currentPan.y})`
      );

      // 应用缩放变换
      const scaleGroup = contentGroup.querySelector('g');
      if (scaleGroup) {
        scaleGroup.setAttribute('transform', `scale(${scale.value})`);
      }
    }

    // 更新网格背景
    requestAnimationFrame(() => {
      if (!svgContainer.value) return;
      
      // 计算网格尺寸
      const gridScale = 100 * scale.value;
      const smallGridScale = 10 * scale.value;
      
      // 设置背景网格大小
      svgContainer.value.style.backgroundSize = 
        `${gridScale}px ${gridScale}px, ${gridScale}px ${gridScale}px, ${smallGridScale}px ${smallGridScale}px, ${smallGridScale}px ${smallGridScale}px`;
      
      // 计算网格偏移
      const offsetX = currentPan.x % gridScale;
      const offsetY = currentPan.y % gridScale;
      const smallOffsetX = currentPan.x % smallGridScale;
      const smallOffsetY = currentPan.y % smallGridScale;
      
      // 设置背景网格位置
      svgContainer.value.style.backgroundPosition = 
        `${offsetX}px ${offsetY}px, ${offsetX}px ${offsetY}px, ${smallOffsetX}px ${smallOffsetY}px, ${smallOffsetX}px ${smallOffsetY}px`;
    });
  };

	/**
	 * 鼠标左键框选节点时处理
	 */
	const handleSelectedCanvasMouseMove = (e: MouseEvent) => {
		
		if(isSelecting.value==false){
			if (!svgContainer.value) return;
			isSelecting.value = true;
			
			// 使用转换方法计算起始位置
			const position = convertToSVGCoordinates(e.clientX, e.clientY);
			selectionStart.x = position.x;
			selectionStart.y = position.y;
			
			// 创建选择框
			selectionRect = createSelectionRect();
			svgContainer.value.appendChild(selectionRect);
			
		}
		
		if (!isSelecting.value || !svgContainer.value) return;
		
		// 使用相同的转换方法计算结束位置
		const position = convertToSVGCoordinates(e.clientX, e.clientY);
		selectionEnd.x = position.x;
		selectionEnd.y = position.y;
		
		// 更新选择框
		if (selectionRect) {
		  const x = Math.min(selectionStart.x, selectionEnd.x) * scale.value + currentPan.x;
		  const y = Math.min(selectionStart.y, selectionEnd.y) * scale.value + currentPan.y;
		  const width = Math.abs(selectionEnd.x - selectionStart.x) * scale.value;
		  const height = Math.abs(selectionEnd.y - selectionStart.y) * scale.value;
		  
		  selectionRect.setAttribute('x', x.toString());
		  selectionRect.setAttribute('y', y.toString());
		  selectionRect.setAttribute('width', width.toString());
		  selectionRect.setAttribute('height', height.toString());
		}
	};
	
	/**
	 * 处理画布左键框选松开事件
	 * @param e 鼠标事件对象
	 */
	const handleSelectedCanvasMouseUp = (_e: MouseEvent) => {
		
		document.removeEventListener('mousemove', handleSelectedCanvasMouseMove);
		document.removeEventListener('mouseup', handleSelectedCanvasMouseUp);
		if (isSelecting.value==true){
			// 计算选择区域
			const x1 = Math.min(selectionStart.x, selectionEnd.x);
			const y1 = Math.min(selectionStart.y, selectionEnd.y);
			const x2 = Math.max(selectionStart.x, selectionEnd.x);
			const y2 = Math.max(selectionStart.y, selectionEnd.y);
			
			const selectedNodes = workflowStore.getSelectedNodes(x1,y1,x2,y2);
			const selectedGroups = workflowStore.getSelectedGroups(x1,y1,x2,y2);
			
			
			if (selectedNodes.length > 0 || selectedGroups.length > 0) {
			  workflowStore.boxSelectElementSettings(selectedNodes, selectedGroups, { x1, y1, x2, y2 });
			} else {
			  workflowStore.clearSelection();
			}
			
			// 清理选择框
			if (selectionRect) {
			  selectionRect.remove();
			  selectionRect = null;
			}
			isSelecting.value = false;
		}else{
			workflowStore.clearSelection();
		}
	};


  // 返回公共接口
  return {
    isPanning,
    currentPan,
    scale,
	handleCanvasMouseDown,
    handleWheel,
    updateTransform,
  };
}; 